﻿using Itech_Run.Domain.Shared.Const;
using Itech_Run.HttpApi.Shared.Options;
using Itech_Run.Sys.Application.Contracts.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using Volo.Abp.Caching;

namespace Itech_Run.Sys.HttpApi.Middleware
{
    public class BaseMiddleware
    {
        private IApplicationBuilder app;
        private readonly IOptions<CacheOptions>? _cacheOptions;
        private readonly IDistributedCache<string?, string> _assemblyCache;
        private readonly IDistributedCache<List<string?>, string> _moduleCache;

        public BaseMiddleware(IApplicationBuilder _app)
        {
            app = _app;
            _cacheOptions = (IOptions<CacheOptions>?)app.ApplicationServices.GetService(typeof(IOptions<CacheOptions>));
            _assemblyCache = (IDistributedCache<string?, string>)app.ApplicationServices.GetService(typeof(IDistributedCache<string?, string>));
            _moduleCache = (IDistributedCache<List<string?>, string>)app.ApplicationServices.GetService(typeof(IDistributedCache<List<string?>, string>));
        }

        protected async Task<string?> GetAssemblyName(ISysModuleService _sysModuleService, string controller)
        {
            var assemblyName = await _assemblyCache.GetOrAddAsync($"Assembly_{controller}",
                  () => _sysModuleService.GetAssemblyName(controller),
                  () => new DistributedCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddSeconds(_cacheOptions?.Value.ControllerAssemblyTime ?? 0) });
            return assemblyName;
        }

        /// <summary>
        /// 获取真实的Controller Name
        /// </summary>
        /// <param name="pathControllerName"></param>
        /// <returns></returns>
        protected string GetActualControllerName(string pathControllerName)
        {
            pathControllerName = pathControllerName.ToLower();
            var allApiControllers = _moduleCache.Get(CacheConst.Module_ApiController_All);
            foreach (string item in allApiControllers)
            {
                if (pathControllerName == item.ToLower())
                {
                    return item;
                }
            }
            return "";
        }
    }
}
